<?php

class PropertyProxy
{
	protected $targetEntity;
    protected $targetProperty;
	protected $entityHandler;

	public function __construct(
        IEntityHandler $entityHandler,
        $targetEntity,
        $targetProperty,
        $type,
        $primaryKey,
        $foreignKey,
        $sqlExtras,
        $customMethod
    )
    {
		$this->entityHandler = $entityHandler;
		$this->targetEntity = $targetEntity;
	}

	public function __call($method, $args)
	{
        $proxiedEntity = $this->loadProperty();
        return call_user_func_array($proxiedEntity->$method, $args);
	}

	public function __get($property)
	{
        $proxiedEntity = $this->loadProperty();
        return $proxiedEntity->$property;
	}

	public function __set($property, $value)
	{
        $proxiedEntity = $this->loadProperty();
        $proxiedEntity->$property = $value;
        return $proxiedEntity;
	}

	public function loadProperty()
	{
        if ($this->customMethod !== null) {

        } else if (!empty($this->primaryKey)) {
            $loadedProperty = $this->entityHandler->getCollection($this->primaryKey, $this->sqlExtras);
        } else if (!empty($this->foreignKey)) {
            $loadedProperty = $this->entityHandler->get($this->foreignKey);
        }

        $targetEntity = $this->targetEntity;
        $targetProperty = $this->targetProperty;
        $targetEntity->$targetProperty = $loadedProperty;
	}

}


class Entity
{
	public $id

	/**
	 * @Proxy("ChildEntity")
	 * @ProxyForeignKey("id")
	 * @ProxySqlExtras("ORDER BY posted ASC LIMIT 1");
	 */
	public $children;

	/**
	 * @Proxy("ParentEntity")
	 * @ProxyPrimaryKey("parentId")
	 */
	public $parent;

	public $parentId;
}